package clubhouse.communication;

import java.util.Vector;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import clubhouse.motioncommand.MotionCommand;

/**
 * @author Anis Darwich & Lionel Croix - Simulation and experimentation on Robot in WSN - WnSN Lab - SJTU
 */
public class TransmissionFifo {
	
	/**Object used to display logs in message log panel.*/
	private final static Logger log = Logger.getLogger(TransmissionFifo.class);
	
	/**The transmission queue vector*/
	private Vector<MotionCommand> motionCom;
	
	/**
	 * Construct the TransmissionFifo object. Instantiate the transmission queue vector.
	 */
	public TransmissionFifo() {
		PropertyConfigurator.configure("log4j.properties");
		this.motionCom = new Vector<MotionCommand>(5,1);
	}
	
	/**
	 * Return the lock used for all synchronization for this object.
	 * @return the value of the lock, true if the object is free, false if it used.
	 */
	protected Object getLock() {
		return this;
	}
	
	/**
	 * Add the specified MotionCommand message to the transmission fifo.
	 * @param msg the MotionCommand message to add in transmission vector.
	 */
	public void txMotionCom(MotionCommand msg) {
		synchronized(this.getLock()) {
			this.motionCom.add(msg);
			log.debug("Added "+ msg.toHexPrint() + " to motionCom\n");
		}
	}
	
	/**
	 * Get the first MotionCommand message from the transmission fifo.
	 * @return the first element of transmission queue, null if this queue is empty.
	 */
	public MotionCommand getMotionCom() {
		synchronized(this.getLock()) {
			if (this.motionCom.size() != 0) {
				MotionCommand tmp = this.motionCom.firstElement();
				this.motionCom.remove(0);
				log.debug("Retrieved "+ tmp.toHexPrint() + " from motionCom\n");
				return tmp;
			} else {
				return null;
			}
		}
	}
	
	/**
	 * Return the number of MotionCommand messages available in the transmission fifo.
	 * @return the size of transmission queue vector.
	 */
	public int motionComAvailable() {
		return this.motionCom.size();
	}
}
